package com.sba.core.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.sba.core.domain.Role;
import com.sba.core.service.RoleService;

/**
 * 
 * @author feiliming
 *
 */
@Controller
@RequestMapping("${ssh.admin-path}/role")
public class RoleController extends BaseController {
	
	private final RoleService roleService;
	
	@Autowired
	public RoleController(RoleService roleService){
		this.roleService = roleService;
	}
	
	@GetMapping
	public String index(){
		return adminThemePath + "/sys/role";
	}
	
	@RequestMapping(path = "/list", method = RequestMethod.GET)
	public @ResponseBody List<Role> getRoles(){
		List<Role> roles = new ArrayList<Role>();
		roles = roleService.getRoles();
		return roles;
	}
	
	@RequestMapping(path = "/save", method = RequestMethod.POST)
	public @ResponseBody JSONObject saveRole(Role role){
		role.setCreateTime(new Date());
		role.setIsSys(0);
		JSONObject obj = new JSONObject();
		try {
			roleService.saveOrUpdate(role);
			obj.put("success", true);
			obj.put("msg", "保存角色成功！");
		} catch (Exception e) {
			obj.put("success", false);
			obj.put("msg", "保存角色失败！");
		}
		return obj;
	}
	
	@RequestMapping(path = "/saveRoleMenu", method = RequestMethod.POST)
	public @ResponseBody JSONObject saveRoleMenu(Role role){
		Role r = roleService.findById(role.getId());
		r.setMenus(role.getMenus());//事物没有关闭？
		JSONObject obj = new JSONObject();
		try {
			roleService.saveOrUpdate(r);
			obj.put("success", true);
			obj.put("msg", "保存角色权限成功！");
		} catch (Exception e) {
			obj.put("success", false);
			obj.put("msg", "保存角色权限失败！");
		}
		return obj;
	}
	
	@GetMapping("/get")
	public @ResponseBody Role getRole(Long id){
		Role role = roleService.findById(id);
		role.getMenus();
		return role;
	}
	
	@RequestMapping(path = "/delete", method = RequestMethod.POST)
	public @ResponseBody JSONObject deleteRole(Long id){
		//角色被用户使用禁止删除，使用异常方式
		
		JSONObject obj = new JSONObject();
		try {
			roleService.delete(id);
			obj.put("success", true);
			obj.put("msg", "删除角色成功！");
		} catch (Exception e) {
			obj.put("success", false);
			obj.put("msg", "删除角色失败！");
		}
		return obj;
	}
	
}
